package logic

import (
	"context"
	"errors"
	"user_srv/cathe"
	"user_srv/models"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	var u models.User
	u.Mobile = in.Mobile
	u.Password = in.Password
	err := u.FindMobile()
	if err != nil {
		logx.Error("查询失败", err)
		return nil, err
	}
	sms := cathe.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if sms.Val() != in.SmsCode {
		logx.Error("短信验证码错误，请重新输入")
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	if u.ID == 0 {
		err = u.Create()
		if err != nil {
			logx.Error("注册失败")
			return nil, errors.New("注册失败")
		}
	}

	return &user.LoginResponse{
		UserId: int64(u.ID),
	}, nil
}
